﻿using ChoJu.Single.DAL;
using ChoJu.Single.ViewModel;
using ChoJu.Single.Views;
using ChoJuRating.View;
using ChongJu.CloudService;
using ChongJu.EventManager;
using ChongJu.GlobalInfo;
using ChongJu.MQTT;
using GalaSoft.MvvmLight.Threading;
using Public.Logger;
using Public.Tools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace ChoJu.Single
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool isUpdate;
        private System.Timers.Timer _timePing;
        private string _address = Tool.GetConfig("ping");
        private CloudService _cloud;

        private DispatcherTimer _timer;

        public MainWindow()
        {
            InitializeComponent();

            //List<double> lst = new List<double>() { 1.64, 2.66, 8.5, 14.19, 19.82, 20.54, 15.69, 11.16, 13.15, 13.58, 13.64, 12.97, 13.49, 12.37, 12.47, 11.97, 12.41, 12.41, 12.41, 12.41, 12.41, 12.41, 12.41, 12.41, 12.41, 12.41 };
            //WeiCalca cala = new WeiCalca(5, 1);
            //for (int i = 0; i < lst.Count; i++)
            //{
            //    var value = lst[i];
            //    var result = cala.InputNew(value);
            //}

            Screen();
            DispatcherHelper.Initialize();
            tbkVersion.Text = Tool.GetAppVersion();
            ucMenu.Width = 0;

            //Task.Run(() => Init());
            Init();
        }

        public int ConvertModbusDataToInt(byte[] modbusResponse, int startIndex = 3)
        {
            if (modbusResponse.Length < startIndex + 2)
                throw new ArgumentException("数据长度不足");

            var by = modbusResponse[startIndex];
            return (modbusResponse[startIndex] << 8) | modbusResponse[startIndex + 1];
        }

        private void Init()
        {
            try
            {
                _cloud = new CloudService();
                GlobalVar.InitGlobalParamer();
                SqliteDal.Instance.Init();

                _timePing = new System.Timers.Timer(1000 * 10);
                _timePing.Elapsed += _timerPing_Elapsed;
                _timePing.Start();
                _timerPing_Elapsed(null, null);

                _timer = new DispatcherTimer();
                _timer.Interval = TimeSpan.FromSeconds(1);
                _timer.Tick += _timer_Tick;
                _timer.Start();

                CommonEvent.MainFromOpacityEventReport += CommonEvent_MainFromOpacityEventReport;

                CloudService service = new CloudService();
                GlobalVar.SiteInfo = service.SearchSiteInfo(GlobalVar.DeviceID, out var isRst);
                if (isRst == true)
                {
                    service.RegistDevice(GlobalVar.DeviceID);
                    CJMsgBox.ShowDialog("需要注册设备，待后台确认\r\n" + GlobalVar.DeviceID, MsgTitle.Warning);
                    Environment.Exit(0);
                }

                APPUpdate();
                MQTTService.Instance.Init(GlobalVar.DeviceID);
                ViewBack(false);

                DataContext = new MainWindowVM();
                tbkDeviceNo.Text = GlobalVar.SiteInfo?.DeviceName;
                if (GlobalVar.DeviceID?.Length > 8)
                    tbkDeviceID.Text = $"*******{GlobalVar.DeviceID?.Substring(7)}";
                else
                    tbkDeviceID.Text = Tool.GetMacAddress();

                //上报版本信息
                service.UploadCurrentVersion(Tool.GetAppVersion(), GlobalVar.GlobalParamer.DllFileName, GlobalVar.DeviceID);

                //上报位置信息
                SendLocation();

                //删除历史日志文件
                DeleteHistoryLogAndVersionFile();

                //上传配置文件信息，后台不存在则上传
                ConfigInfo();
            }
            catch(Exception ex)
            {
                Logger.Error("主页面构造函数初始化异常", ex);
            }
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            tbkTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void CommonEvent_MainFromOpacityEventReport(bool obj)
        {
            ViewBack(obj);
        }

        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (ucMenu.Width == 0)
                ucMenu.Width = 50;
            else
                ucMenu.Width = 0;
        }

        private void _timerPing_Elapsed(object sender, ElapsedEventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                var temp = PingSomeSite(_address);
                GlobalVar.NetworkDelay = temp;
                Dispatcher.Invoke(() => 
                {
                    tbkDelay.Foreground = temp > 0 ? Brushes.White : Brushes.Red;
                    tbkDelay.Text = temp > 0 ? temp.ToString() : "网络异常";
                    tbkDelay.FontSize = temp > 0 ? 13 : 23;
                });
            });
        }

        private long PingSomeSite(string Address)
        {
            try
            {
                Ping ping = new Ping();
                PingReply re = ping.Send(Address, 1000);
                var time = re.RoundtripTime; //ms
                return re.Status == IPStatus.Success ? time : -1;
            }
            catch(Exception ex)
            {
                return -1;
            }
        }

        private void Screen()
        {
            Screen primaryScreen = System.Windows.Forms.Screen.PrimaryScreen;
            int width = primaryScreen.Bounds.Width;
            int height = primaryScreen.Bounds.Height;
            if (width == 1280)
                this.WindowState = WindowState.Maximized;
        }

        private void ViewBack(bool view)
        {
            Dispatcher.Invoke(() =>
            {
                bodBack.Visibility = view ? Visibility.Visible : Visibility.Collapsed;
            });
        }

        private void APPUpdate()
        {
            try
            {
                if (GlobalVar.SiteInfo == null)
                {
                    Dispatcher.Invoke(() => CJMsgBox.ShowDialog("服务请求异常，不检查系统更新"));
                    return;
                }

                if (string.IsNullOrWhiteSpace(GlobalVar.SiteInfo.TargetVersion) == true)
                    return;

                string curAppVersion = Tool.GetAppVersion();
                if (curAppVersion == GlobalVar.SiteInfo.TargetVersion)
                    return;

                if (string.IsNullOrWhiteSpace(GlobalVar.SiteInfo.TargetVersion) == false)
                {
                    var update = new APPUpdateView(curAppVersion, GlobalVar.SiteInfo.TargetVersion);
                    update.ShowDialog();

                    isUpdate = update.IsUpdate;
                    if (update.IsUpdate == true)
                        Dispatcher.Invoke(() => 
                        {
                            Environment.Exit(0);
                            Close();
                        });
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void SendLocation()
        {
            Task.Run(() =>
            {
                try
                {
                    var info = new LocationDal().GetLocationByIP();
                    if (info == null)
                        return;

                    new CloudService().SendLocation(info.Country, info.RegionName, info.City, info.Query, info.Lat, info.Lon, GlobalVar.DeviceID);
                }
                catch(Exception ex)
                {
                    Logger.Error("上报地理位置异常", ex);
                }
            });
        }

        /// <summary>
        /// 删除一月之前的日志
        /// </summary>
        private void DeleteHistoryLogAndVersionFile()
        {
            //删除一月之前的所有日志
            var root = System.IO.Path.Combine(AppContext.BaseDirectory, "Log");
            var dirs = Directory.GetDirectories(root).Where(w => w.Contains("年")).ToList();
            foreach (var dir in dirs)
            {
                var files = Directory.GetFiles(dir);
                foreach (var file in files)
                {
                    var name = new FileInfo(file).Name;
                    var arr = name.Split('_');
                    var temp = arr[0].Replace("年", "-").Replace("月", "-").Replace("日", " ");
                    var bol = DateTime.TryParse(temp, out var date);
                    if(bol == true & (DateTime.Now - date).Days > 30)
                        File.Delete(file);
                }
            }

            //删除不是本年度的版本包文件
            root = System.IO.Path.Combine(AppContext.BaseDirectory, "Version");

            //获取所有文件夹
            dirs = Directory.GetDirectories(root).ToList(); 
            foreach (var dir in dirs)
            {
                DateTime creationTime = Directory.GetCreationTime(dir);
                if(creationTime.Year != DateTime.Now.Year)
                    Directory.Delete(dir, true);
            }

            //获取所有压缩包文件  zip
            var zips = Directory.GetFiles(root).ToList();
            foreach(var zip in zips)
            {
                DateTime creationTime = File.GetCreationTime(zip);
                if (creationTime.Year != DateTime.Now.Year)
                    File.Delete(zip);
            }
        }

        private void ConfigInfo()
        {
            var exist = _cloud.ConfigFileExist(GlobalVar.DeviceID);
            if (exist != false)
                return;

            _cloud.UploadConfigFiles(GlobalVar.DeviceID);
        }
    }
}
